package com.example.h5server.controller;

import com.example.h5server.model.EmployeeData;
import com.example.h5server.service.ExcelExportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name = "通用webApi")
public class ExportExcelController {
    @Autowired
    private ExcelExportService excelExportService;

    @PostMapping("/exportEmployeeExcel")
    @Operation(summary = "导出成员信息表格")
    public void exportEmployeeExcel(
            @RequestBody(required = false) List<EmployeeData> employeeList,
            @RequestParam(required = false, defaultValue = "员工信息.xlsx") String fileName,
            HttpServletResponse response) {
        try {
            // 如果没有传入数据，则使用模拟数据
            if (employeeList == null || employeeList.isEmpty()) {
                employeeList = getEmployeeData();
            }

            excelExportService.writeEmployeeExcelToResponse(employeeList, response, fileName);
        } catch (Exception e) {
            // 添加错误响应处理
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("导出Excel失败: " + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }


    // 模拟数据获取方法
    private List<EmployeeData> getEmployeeData() {
        return Arrays.asList(
                new EmployeeData() {{
                    setDepartment("测试1");
                    setName("测试");
                    setPosition("测试");
                    setLevel("高层");
                    setPerformance("优秀");
                    setDepartmentName("测试1");
                }},
                new EmployeeData() {{
                    setDepartment("测试1/测试4");
                    setName("测试");
                    setPosition("测试");
                    setLevel("一线");
                    setPerformance("优秀");
                    setDepartmentName("测试4");
                }},
                new EmployeeData() {{
                    setDepartment("测试1/测试4");
                    setName("测试");
                    setPosition("测试");
                    setLevel("高层");
                    setPerformance("优秀");
                    setDepartmentName("测试4");
                }}
        );
    }
}
